<?php

declare(strict_types=1);

namespace Application\Queue;

use \Illuminate\Support\Collection;
use JetBrains\PhpStorm\Pure;

/**
 * Class Storage
 *
 * @package Application\Queue
 */
class Storage
{
    protected Collection $collection;

    /**
     * Storage constructor.
     */
    public function __construct()
    {
        $this->collection = new Collection();
    }

    /**
     * Save the message.
     *
     * @param string $queue
     * @param string $message
     */
    public function push(string $queue, string $message)
    {
        /** @var \SplQueue $queueObject */
        $queueObject = $this->collection->get($queue, null);
        if (is_null($queueObject)) {
            $queueObject = new \SplQueue();
            $this->collection->put($queue, $queueObject);
        }

        $queueObject->push($message);
    }

    /**
     * Launch the message.
     *
     * @param string $queue
     * @return string|null
     */
    public function pop(string $queue): ?string
    {
        /** @var \SplQueue $queueObject */
        $queueObject = $this->collection->get($queue, null);
        if (is_null($queueObject)) {
            return null;
        }

        $result = $queueObject->pop();

        if ($queueObject->isEmpty()) {
            $this->collection->forget($queue);
        }

        return $result;
    }

    /**
     * Is there a queue.
     *
     * @param string $queue
     * @return bool
     */
    public function queueExists(string $queue): bool
    {
        return $this->collection->offsetExists($queue);
    }

    /**
     * The number of queue.
     *
     * @return int
     */
    #[Pure] public function queueCount(): int
    {
        return $this->collection->count();
    }

    /**
     * Is the queue empty.
     *
     * @param string $queue
     * @return bool
     */
    public function queueIsEmpty(string $queue): bool
    {
        /** @var \SplQueue $queueObject */
        $queueObject = $this->collection->get($queue, null);
        if (is_null($queueObject)) return true;

        return $queueObject->isEmpty();
    }
}